import { MimeType } from "@/constant";

/**
 * 读取文件流base64字符串
 * @param {} file 
 * @param {*} loaded 
 * @param {*} exception 
 */
export const UploadReadFile = (file, loaded, exception) => {
    const reader = new FileReader()
    // reader.readAsArrayBuffer(file)
    reader.readAsDataURL(file)
    reader.onload = () => {
        loaded(reader.result);
    }
    reader.onerror = () => {
        if (exception) {
            exception(error);
        }
    }
}
/**
 * 将base64字符串实现文件下载
 * @param {*} base64 
 * @param {*} fileName 
 */
export const DownloadBinaryFile = (base64, fileName) => {
    const extension = fileName.split('.').pop().toLowerCase()
    const mime = Object.values(MimeType)[Object.keys(MimeType).indexOf(extension)]
    if (base64.indexOf(base64) > 0) {
        base64 = base64.split(',').pop()//只保留base64,之后的
    }
    const byteCharacters = atob(base64)//此次base64不能包含头部
    let byteArrays = []
    for (var i = 0; i < byteCharacters.length; i++) {
        byteArrays.push(byteCharacters.charCodeAt(i))
    }
    let byteArray = new Uint8Array(byteArrays)
    const blob = new Blob([byteArray], { type: mime })
    const link = document.createElement('a')
    let url = window.URL || window.webkitURL || window.moxURL
    url = url.createObjectURL(blob)
    link.href = url
    link.download = fileName

    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
}
/**
 * 将权限树转为列表
 * @param {*} data 树形权限
 * @returns 
 */
export const PermissionTree2List = (data) => {
    let node = [];
    if (data && data.length > 0) {
        for (let item of data) {
            let tmp = {
                permissionId: item.permissionId,
                permissionName: item.permissionName,
                permissionCode: item.permissionCode,
                url: item.url,
                type: item.type,
                parentId: item.parentId,
                hasChildren: item.hasChildren,
                children: []
            }

            if (item.children && item.children.length > 0) {
                const children = PermissionTree2List(item.children);
                node.push(...children);
            }
            node.push(tmp);
        }
    }
    return node;
}